package com.ruoyi.labdata.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.labdata.domain.LabFlowInstance;
import com.ruoyi.labdata.domain.LabFlowNode;
import com.ruoyi.labdata.domain.LabFlowTask;
import com.ruoyi.labdata.mapper.LabFlowInstanceMapper;
import com.ruoyi.labdata.service.ILabFlowInstanceService;
import com.ruoyi.labdata.service.ILabFlowNodeService;
import com.ruoyi.labdata.service.ILabFlowTaskService;
import com.ruoyi.system.service.ISysDeptService;

/**
 * 工作流实例Service业务层处理
 * 
 * @author winner pan
 * @date 2022-03-11
 */
@Service
public class LabFlowInstanceServiceImpl implements ILabFlowInstanceService {
	@Autowired
	private LabFlowInstanceMapper labFlowInstanceMapper;
	
	@Autowired
	private ILabFlowTaskService labFlowTaskService;
	@Autowired
	private ILabFlowNodeService labFlowNodeService;
	
	@Autowired
	private ISysDeptService deptService;

	/**
	 * 查询工作流实例
	 * 
	 * @param instanceId
	 *            工作流实例ID
	 * @return 工作流实例
	 */
	@Override
	public LabFlowInstance selectLabFlowInstanceById(Long instanceId) {
		return labFlowInstanceMapper.selectLabFlowInstanceById(instanceId);
	}

	/**
	 * 查询工作流实例列表
	 * 
	 * @param labFlowInstance
	 *            工作流实例
	 * @return 工作流实例
	 */
	@Override
	public List<LabFlowInstance> selectLabFlowInstanceList(LabFlowInstance labFlowInstance) {
		return labFlowInstanceMapper.selectLabFlowInstanceList(labFlowInstance);
	}

	/**
	 * 新增工作流实例
	 * 
	 * @param labFlowInstance
	 *            工作流实例
	 * @return 结果
	 */
	@Override
	public int insertLabFlowInstance(LabFlowInstance labFlowInstance) {
		if(labFlowInstance.getFlowStatusOpt()==null){
			labFlowInstance.setFlowStatusOpt("uncommitted");
		}
		return labFlowInstanceMapper.insertLabFlowInstance(labFlowInstance);
	}
	@Override
	@Transactional
	public int commitFlow(LabFlowInstance labFlowInstance){
		//读取所有节点
		Date currentDate = new Date();
		LabFlowNode queryNode = new LabFlowNode();
		if(labFlowInstance.getInstanceId()==null){
			throw new RuntimeException("流程实例ID:instanceId 为空.");
		}
		if(labFlowInstance.getWorkflowId()==null){
			throw new RuntimeException("流程定义ID:workflowId 为空.");
		}
		LabFlowInstance oldlabFlowInstance = labFlowInstanceMapper.selectLabFlowInstanceById(labFlowInstance.getInstanceId());
		SysDept sysDept = this.deptService.selectDeptById(oldlabFlowInstance.getCreateOrgId());
		queryNode.setWorkflowId(oldlabFlowInstance.getWorkflowId());
		List<LabFlowNode> labFlowNodeList = labFlowNodeService.selectLabFlowNodeList(queryNode);
		int index = 0;
		StringBuffer flowRoles = new StringBuffer();
		for(LabFlowNode item : labFlowNodeList){
			LabFlowTask task = new LabFlowTask();
			//task.setNodeId(item.getNodeId());
			task.setNodeName(item.getNodeName());
			
			//直接读取用户ID保存到流程中
			if(item.getApprovalRoles()!=null){
				String doUserIds = null;
				if(item.getNodeTypeOpt().equals("1")){
					doUserIds = labFlowNodeService.getUserIdsByDeptRole(item.getApprovalRoles(), sysDept.getAncestors(), sysDept.getDeptId());
				}else{
					doUserIds = labFlowNodeService.getUserIdsByRole(item.getApprovalRoles());
				}
				if(StringUtils.isEmpty(doUserIds)){
					throw new RuntimeException("流程节点："+item.getNodeName()+" 的执行角色找不到相应的执行人,请为发起人的部门或其上级部门配备该角色的执行人员.");
				}
				if(doUserIds.length()>=500){
					throw new RuntimeException("流程节点："+item.getNodeName()+" 的执行角色对应的执行人员太多，请重新配置改节点角色.");
				}
				task.setNodeUsers(doUserIds);
			}
			
			
			
			task.setInstanceId(oldlabFlowInstance.getInstanceId());
			task.setNodeNo(item.getNodeNo());
			task.setTaskStatusOpt("unsigned");
			task.setApprovalTypeOpt(item.getApprovalTypeOpt());
			StringBuffer operation = new StringBuffer();
			if(item.getPassed()){
				operation.append("passed");
			}
			if(item.getRefused()){
				if(operation.length()>0){
					operation.append(",");
				}
				operation.append("refused");
			}
			if(item.getRectify()){
				if(operation.length()>0){
					operation.append(",");
				}
				operation.append("rectify");
			}
			task.setOperation(operation.toString());
			if(index==0){
				task.setTaskStatusOpt("completed");
				task.setSignUser(oldlabFlowInstance.getCreateBy());
				task.setSignTime(currentDate);
				task.setFinishTime(task.getSignTime());
				task.setFinishFlagOpt("passed");
				task.setFinishComments("流程提交");
			}
			if(index>0 && index<labFlowNodeList.size() && item.getApprovalRoles()!=null){
				if(flowRoles.length()>0){
					flowRoles.append(",");
				}
				flowRoles.append(item.getApprovalRoles());
			}
			if(labFlowInstance.isFinish()){
				task.setTaskStatusOpt("completed");
				task.setSignUser("admin");
				task.setSignTime(currentDate);
				task.setFinishTime(task.getSignTime());
				task.setFinishFlagOpt("passed");
				task.setFinishComments(labFlowInstance.getFinishMark());
				if(index + 1==labFlowNodeList.size()){
					task.setIsCurrentOpt(1);
				}
			}else if(index==1){
				task.setIsCurrentOpt(1);
			}
			index ++;
			labFlowTaskService.insertLabFlowTask(task);
		}
		oldlabFlowInstance.setFlowStatusOpt("committed");
		oldlabFlowInstance.setStartTime(currentDate);
		oldlabFlowInstance.setFlowRoles(flowRoles.toString());
		if(labFlowInstance.isFinish()){
			oldlabFlowInstance.setFlowStatusOpt("finished");
			oldlabFlowInstance.setEndTime(currentDate);
		}
		return this.updateLabFlowInstance(oldlabFlowInstance);
	}
	
	/**
	 * 修改工作流实例
	 * 
	 * @param labFlowInstance
	 *            工作流实例
	 * @return 结果
	 */
	@Override
	public int updateLabFlowInstance(LabFlowInstance labFlowInstance) {
		int ret = labFlowInstanceMapper.updateLabFlowInstance(labFlowInstance);
		if(ret==0){
			throw new RuntimeException("流程已经提交，不能再修改或者提交");
		}
		return ret;
	}

	/**
	 * 批量删除工作流实例
	 * 
	 * @param instanceIds
	 *            需要删除的工作流实例ID
	 * @return 结果
	 */
	@Override
	public int deleteLabFlowInstanceByIds(Long[] instanceIds) {
		return labFlowInstanceMapper.deleteLabFlowInstanceByIds(instanceIds);
	}

	/**
	 * 删除工作流实例信息
	 * 
	 * @param instanceId
	 *            工作流实例ID
	 * @return 结果
	 */
	@Override
	public int deleteLabFlowInstanceById(Long instanceId) {
		int ret = labFlowInstanceMapper.deleteLabFlowInstanceById(instanceId);
		if(ret==0){
			throw new RuntimeException("该流程不存在或已经提交，不能被删除!");
		}
		return ret;
	}
	@Override
	public int  withDrawLabFlowInstance(Long instanceId){
		return labFlowInstanceMapper.withDrawLabFlowInstance(instanceId);
	}
	
	public List<LabFlowInstance> selectCopyList(LabFlowInstance labFlowInstance){
		return labFlowInstanceMapper.selectCopyList(labFlowInstance);
	}
    public List<LabFlowInstance> selectFinsihedList(LabFlowInstance labFlowInstance){
    	return labFlowInstanceMapper.selectFinsihedList(labFlowInstance);
    }
    
    public List<LabFlowInstance> selectCommittedList(LabFlowInstance labFlowInstance){
    	return labFlowInstanceMapper.selectCommittedList(labFlowInstance);
    }
    
    public List<LabFlowInstance> selectMyList(LabFlowInstance labFlowInstance){
    	return labFlowInstanceMapper.selectMyList(labFlowInstance);
    }
    public int finishLabFlowInstance(LabFlowInstance labFlowInstance){
    	int ret =  labFlowInstanceMapper.finishLabFlowInstance(labFlowInstance);
    	if(ret==0){
    		throw new RuntimeException("流程已经结束，不能再执行结束操作.");
    	}
    	return ret;
    }
}
